from gevent import monkey, spawn

monkey.patch_socket()
import re
from lib.RestfulAttack import RestfulAttack
import random
import subprocess

dictionary = dict()
dictionary["driver"] = "WebDriver Hub"
dictionary["tomcat"] = "401 Unauthorized"
dictionary["jenkins"] = "http://eclipse.org/jetty"


class Finger(RestfulAttack):
    def __init__(self, data, port, concurrent):
        super().__init__(data, int(concurrent))
        self.port = str(port)

    def size(self):
        raise len(self.data)

    def do_work(self, row):
        try:
            ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", row)[0]
            url = "http://" + ip + ":" + self.port + "/wd/hub/static/resource/hub.html"

            r = self.get_http1_0(url=url, timeout=8, allow_redirects=False)

            server = " ****"
            for k, v in dictionary.items():
                if v in r:
                    server = k
                    break

            if 'driver' in server:
                print("***One Service:", server)
                subprocess.call("echo -e \"{}\" >> driver".format(ip), shell=True)


        except Exception as e:
            pass

        finally:
            now = self.timer.toc()

            if random.randint(1, 10) > 9:
                print(str(self.timer.calls * 100 / len(self.data))[0:4] + "%",
                      " use_time:  ", now,
                      " total_time:  ", (now / self.timer.calls) * len(self.data))


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', dest='file', help='port')
    parser.add_argument('-p', dest='port', help='port')
    parser.add_argument('-t', dest='thr', help='thr')

    args = parser.parse_args()

    assert args.file is not None
    assert args.port is not None
    try:
        pure_data = open(args.file, 'r').readlines()[1:-1]
        finger = Finger(pure_data, args.port, concurrent=args.thr)
        finger.run()
    except:
        pass
